package com.chx.service.Impl;

import com.chx.constant.MessageConstant;
import com.chx.constant.PasswordConstant;
import com.chx.constant.StatusConstant;
import com.chx.context.BaseContext;
import com.chx.dto.UserDto;
import com.chx.dto.UserLoginDto;
import com.chx.dto.UserPageQueryDto;
import com.chx.dto.UserPasswordDto;
import com.chx.entity.Users;
import com.chx.exception.AccountLockedException;
import com.chx.exception.AccountNotFoundException;
import com.chx.exception.AccountNotPowerException;
import com.chx.exception.PasswordEditFailedException;
import com.chx.mapper.RoleMapper;
import com.chx.mapper.UserMapper;
import com.chx.result.PageResult;
import com.chx.service.UserService;
import com.chx.wrapper.UserWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author cp-月入过万
 * @Date 2025/5/29
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;
    @Override
    public Users login(UserLoginDto userLoginDto) {
        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword();
        //1、根据用户名查询用户
        Users users = userMapper.getByUsername(username);
        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if(users == null)
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        if(Objects.equals(users.getStatus(), StatusConstant.DISABLE))
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!users.getPassword().equals(password))
            throw new AccountNotFoundException(MessageConstant.PASSWORD_ERROR);

        //3、返回用户信息

        return users;
    }

    @Override
    public void save(UserDto userDto) {
        Users users = new Users();
        //对象拷贝
        BeanUtils.copyProperties(userDto, users);

        //设置状态，默认正常状态
        users.setStatus(StatusConstant.ENABLE);

        //设置默认密码，对密码进行md5加密处理
        users.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        if(Objects.equals(BaseContext.getCurrentId(), StatusConstant.SUPER_ADMIN))
            userMapper.insert(users);
        else
            throw new AccountNotPowerException(MessageConstant.ACCOUNT_NOT_POWER);
    }

    @Override
    public void update(UserDto userDto) {
        Users users = new Users();
        BeanUtils.copyProperties(userDto, users);
        if(Objects.equals(BaseContext.getCurrentId(), StatusConstant.SUPER_ADMIN) || Objects.equals(BaseContext.getCurrentId(), users.getUserId()))
            userMapper.update(users);
        else
            throw new AccountNotPowerException(MessageConstant.ACCOUNT_NOT_POWER);
    }

    @Override
    public void updateStatus(Integer status, Long id) {
        Users users = Users.builder()
                .userId(id)
                .status(status)
                .build();
        if(Objects.equals(BaseContext.getCurrentId(), StatusConstant.SUPER_ADMIN))
            userMapper.update(users);
        else
            throw new AccountNotPowerException(MessageConstant.ACCOUNT_NOT_POWER);
    }

    @Override
    public void resetPassword(Long id) {
        Users users = Users.builder()
                .userId(id)
                .password(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()))
                .build();
        if (Objects.equals(BaseContext.getCurrentId(), StatusConstant.SUPER_ADMIN))
            userMapper.update(users);
        else
            throw new AccountNotPowerException(MessageConstant.ACCOUNT_NOT_POWER);
    }

    @Override
    public Users getById(Long id) {
        Users users = userMapper.getById(id);
        users.setPassword(PasswordConstant.ENCRYPT_PASSWORD);
        return users;
    }

    @Override
    public PageResult page(UserPageQueryDto userPageQueryDto) {
        //开始分页查询
        PageHelper.startPage(userPageQueryDto.getPage(), userPageQueryDto.getPageSize());

        //查询分页数据
        Page<Users> page = userMapper.pageQuery(userPageQueryDto);

        long total = page.getTotal();
        List<Users> records = page.getResult();

        for(Users record : records)
            record.setPassword(PasswordConstant.ENCRYPT_PASSWORD);
        List<UserWrapper> userWrappers = records.stream().map(record -> {
            String roleName = roleMapper.getById(record.getRoleId()).getRoleName();
            return new UserWrapper(record, roleName);
        }).collect(Collectors.toList());
        return new PageResult(total, userWrappers);
    }

    @Override
    public void updatePassword(UserPasswordDto userPasswordDto) {
        if(!Objects.equals(DigestUtils.md5DigestAsHex(userPasswordDto.getOldPassword().getBytes()), userMapper.getById(userPasswordDto.getUserId()).getPassword()))
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_ERROR);
        if(!userPasswordDto.getNewPasswordOne().equals(userPasswordDto.getNewPasswordTwo()))
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_EDIT_SUCCESS);
        Users users = Users.builder()
                .userId(userPasswordDto.getUserId())
                .password(DigestUtils.md5DigestAsHex(userPasswordDto.getNewPasswordOne().getBytes()))
                .build();
        userMapper.update(users);
    }
}
